#!/bin/bash

#$1 is the path to the program folder being installed. For example, ~/pi-apps/apps/Arduino
#Example usage: ~/pi-apps/uninstall-installed ~/pi-apps/apps/Arduino

#app name
app="$(basename "$1")"

function error {
  echo -e "\e[91m$1\e[39m"
  exit 1
}

reduceapt() { #remove unwanted lines from apt output
  grep -v "apt does not have a stable CLI interface.\|Reading package lists...\|Building dependency tree\|Reading state information...\|Need to get\|After this operation,\|Get:\|Fetched\|Selecting previously unselected package\|Preparing to unpack\|Unpacking \|Setting up \|Processing triggers for "
}

DIRECTORY="$(readlink -f "$(dirname "$0")")"

echo -e "\e[97m\nRunning purge-installed...\e[39m"

if [ -z "$app" ];then
  error "No app name specified to purge-installed!"
fi

source "${DIRECTORY}/api" || error "Failed to source $DIRECTORY/api."

apt_lock_wait

#to avoid issues with symbols and spaces in app names, we shasum the app name for use in apt
appnamehash="$(echo "$app" | md5sum | cut -c1-8 | awk '{print $1}')"

#if dummy deb found/installed
if dpkg -l pi-apps-$appnamehash &>/dev/null ;then
  #new pkg-install implementation - using dummy debs
  
  echo -e "\e[97m\nRemoving dummy deb for $app...\e[39m"
  sudo -E apt purge -y pi-apps-$appnamehash --autoremove 2>&1 | reduceapt || error "apt failed to purge dummy deb (pi-apps-$appnamehash)!"
  
elif [ -f "${DIRECTORY}/data/installed-packages/${app}" ];then
  #old pkg-install implementation
  echo -e "\e[93m\nWARNING! pkg-install is using the legacy implementation - an installed-packages file instead of a dummy deb\e[39m"
  
  PKG_LIST="$(cat "${DIRECTORY}/data/installed-packages/${app}" | tr '\n' ' ' | sed 's/  / /g')"
  
  PURGE_LIST="$(sudo -E apt-get purge --dry-run $PKG_LIST | sed -n '/The following packages will be REMOVED/,/to remove and/p' | sed -e '2,$!d' -e '$d' | tr -d '*' | tr '\n' ' ' | sed 's/The following.*//')"
  echo "These packages will be purged: $PURGE_LIST"
  
  #normal mode
  output="$(sudo LANG=C LC_ALL=C apt purge -y $PKG_LIST 2>&1)"
  exitcode=$?
  
  errors="$(echo "$output" | grep '^[(W)|(E)|(Err]:')"
  if [ $exitcode != 0 ] || [ ! -z "$errors" ];then
    echo -e "\e[91mFailed to uninstall the packages!\e[39m"
    echo -e "APT reported these errors:\n\e[91m$errors\e[39m"
    exit 1
  fi
else
  echo "purge-installed: Neither dummy deb nor installed-packages file detected. Nothing to do!"
fi

echo
status_green "All packages have been purged succesfully."
rm -f "${DIRECTORY}/data/installed-packages/${app}"
